//
//  DiscoverViewController.m
//  ShanghaiShopping
//
//  Created by KDC on 2019/8/22.
//  Copyright © 2019 KDC. All rights reserved.
//

#import "DiscoverViewController.h"
#import "DiscoverTableViewCell.h"
#import "JSONDiscoverModel.h"
#import "WKWebViewController.h"

@interface DiscoverViewController () <UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UIImageView *headerView;
@property (nonatomic, strong) UIView *tabHeaderView;
@property (nonatomic, strong) UIScrollView *topNavScroll;

@property (nonatomic, strong) UILabel *lbTitle;
@property (nonatomic, strong) UILabel *lbPresentation;

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIImageView *image2;
@property (nonatomic, strong) UIButton *image3;
@property (nonatomic, strong) UILabel *image3Lable;
@property (nonatomic, assign) CGFloat offset;

@property (nonatomic, strong) NSMutableArray *dataArr;

@property (nonatomic, strong) NSMutableArray *tableViewDataArr;

@property (nonatomic, assign) NSInteger refreshCount;//上滑次数
@property (nonatomic, assign) NSInteger totalCount;//列表个数

@property (nonatomic, copy) NSString *topNavId;//当前选中的Nav ID
@property (nonatomic, assign) NSInteger index;//当前选中的Nav index


@property (nonatomic, strong) NSMutableArray *navDataArr;//导航栏数据


@property (nonatomic, assign) NSInteger enterIntoCount;//进入当前页面次数

@property (nonatomic, strong) JSONListTweetModel *shareDataModel;
@property (nonatomic, strong) NSDictionary *shareDicData;



@end

@implementation DiscoverViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO];
}

- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.index = 0;
    //布局UI
    [self createUI];
    [self.view addSubview:self.tableView];
    
    // 添加头部的下拉刷新
    MJRefreshNormalHeader *header = [[MJRefreshNormalHeader alloc] init];
    [header setRefreshingTarget:self refreshingAction:@selector(headerClick)];
    self.tableView.mj_header = header;
    [self.tableView.mj_header beginRefreshing];
    
    // 添加底部的上拉加载
    MJRefreshBackNormalFooter *footer = [[MJRefreshBackNormalFooter alloc] init];
    [footer setRefreshingTarget:self refreshingAction:@selector(footerClick)];
    self.tableView.mj_footer = footer;
    
    self.tableView.rowHeight = UITableViewAutomaticDimension; // 自适应xib高度
    self.tableView.estimatedRowHeight = 200; //先估计一个高度
}
// 头部的下拉刷新触发事件
- (void)headerClick {
    self.refreshCount = 1;
    [self loadData];
    // 结束刷新
    [self.tableView.mj_header endRefreshing];
}
// 底部的上拉加载触发事件
- (void)footerClick {
    self.refreshCount++;
    [self addData];
}

- (void)updateUIWith:(NSMutableArray *)dataArr index:(NSInteger)index {
    if (self.tableViewDataArr.count != 0) {
        [self.tableViewDataArr removeAllObjects];
    }
    JSONDiscoverModel *model = dataArr[index];
    [self.image2 sd_setImageWithURL:[NSURL URLWithString:DSStringValue(model.imgPath)] placeholderImage:LHYPlaceholderImage];
    [self.image3 sd_setImageWithURL:[NSURL URLWithString:DSStringValue(model.imgPath)] forState:UIControlStateNormal placeholderImage:LHYPlaceholderImage];
    
    self.image3Lable.text = DSStringValue(model.navName);
    self.lbTitle.text = DSStringValue(model.title);
    self.lbPresentation.text = DSStringValue(model.presentation);
    [self.tableViewDataArr addObjectsFromArray:model.listTweet];
    [self.tableView reloadData];
}

- (void)loadData {

    if (self.dataArr.count != 0) {
        [self.dataArr removeAllObjects];
    }
    [PPNetworkHelper POST:URL_getFindInit parameters:nil success:^(id responseObject) {
        JSONDiscoverModel *model;
        
        for (int i = 0; i < [responseObject[@"retBody"] count]; i++) {
            model = [[JSONDiscoverModel alloc] initWithDictionary:responseObject[@"retBody"][i] error:nil];
            
            [self.dataArr addObject:model];
            [self.navDataArr addObject:responseObject[@"retBody"][i][@"navName"]];
        }
        if (self.enterIntoCount == 0) {//首次进入当前页面
            [self addNav];
            self.enterIntoCount++;
        }
      
        [self updateUIWith:self.dataArr index:self.index];
    } failure:^(NSError *error) {
        [SXLoadingView showAlertHUD:SXLoadingErrorStr duration:SXLoadingTime];
    }];
}

- (void)addData {
    if (IsNotNilArr(self.dataArr)) {
        
        JSONDiscoverModel *model = self.dataArr[0];
        if (self.topNavId == nil) {
            self.topNavId = model.id;
        }
        NSDictionary *par = @{@"page":@(self.refreshCount),
                              @"pageSize":@"5",
                              @"topNavId":self.topNavId
                              };
        
        [PPNetworkHelper POST:URL_getFindNext parameters:par success:^(id responseObject) {
            NSArray *arr = responseObject[@"retBody"][@"rows"];
            self.totalCount = [responseObject[@"retBody"][@"total"] integerValue];
            if (IsNotNilArr(arr)) {
                [self.tableViewDataArr addObjectsFromArray:arr];
            }
            [self.tableView reloadData];
        } failure:^(NSError *error) {
            [SXLoadingView showAlertHUD:SXLoadingErrorStr duration:SXLoadingTime];
        }];
    }
}

- (void)actionTopImage {
    JSONDiscoverModel *model = self.dataArr[self.index];
    WKWebViewController *vc = [[WKWebViewController alloc] initWithURLString:model.linkPath];
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)createUI {
    _tabHeaderView = [[UIView alloc] init];
    //顶部Nav背景图
    //顶部背景图
    self.image2 = [[UIImageView alloc] initWithFrame:CGRectMake(0, -kStatusBarHeight, SCREEN_WIDTH, ADAPT_W(240))];
    DRNRealTimeBlurView *blurView2 = [[DRNRealTimeBlurView alloc] initWithFrame:self.image2.bounds];
    [self.image2 addSubview:blurView2];
    self.image2.image = LHYPlaceholderImage;
    
    //圆角图
    self.image3 = [[UIButton alloc] initWithFrame:CGRectMake(ADAPT_W(16), ADAPT_W(112) - kStatusBarHeight, SCREEN_WIDTH - ADAPT_W(32), ADAPT_W(180))];
    self.image3.backgroundColor = LHYPlaceholderColor;
    self.image3.layer.cornerRadius = 10;//圆角
    self.image3.layer.masksToBounds = YES;
    [self.image3 setImage:LHYPlaceholderImage forState:UIControlStateNormal];
    [self.image3 addTarget:self action:@selector(actionTopImage) forControlEvents:UIControlEventTouchUpInside];

    [self.tabHeaderView addSubview:self.image2];
    [self.tabHeaderView addSubview:self.image3];
   //原生毛玻璃
//    UIBlurEffect *blur = [UIBlurEffect effectWithStyle:UIBlurEffectStyleDark];
//    UIVisualEffectView *effectview = [[UIVisualEffectView alloc] initWithEffect:blur];
//    effectview.frame = self.image2.bounds;
//    effectview.alpha = 0.96;
//    [self.image2 addSubview:effectview];
    
    self.image3Lable = [[UILabel alloc] initWithFrame:CGRectMake(0, (self.image3.frame.size.height - 50) / 2, self.image3.frame.size.width, 50)];
    self.image3Lable.font = FONT_BOLD(36);
    self.image3Lable.textColor = [UIColor whiteColor];
    self.image3Lable.textAlignment = YES;
    self.image3Lable.hidden = YES;
    [self.image3 addSubview:self.image3Lable];
    
    UIImageView *imageLeftTop = [[UIImageView alloc] initWithFrame:CGRectMake(-15, 16, 75, 45)];
    imageLeftTop.image = ImageNamed(@"dis_recommend");
    [self.image3 addSubview:imageLeftTop];
    
    
    UILabel *lb = [[UILabel alloc] init];
    self.lbTitle = lb;
    [_tabHeaderView addSubview:lb];
    lb.font = FONT(16);
    [lb mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(16);
        make.right.mas_offset(-16);
        make.top.mas_equalTo(self.image3.mas_bottom).mas_offset(18);
        make.height.mas_equalTo(23);
    }];
    
    UILabel *lbDetail = [[UILabel alloc] init];
    self.lbPresentation = lbDetail;
    [_tabHeaderView addSubview:lbDetail];
    lbDetail.font = FONT(13);
    lbDetail.numberOfLines = 0;
    lbDetail.textColor = UIColorFromRGB(0x555555);
    [lbDetail mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(16);
        make.right.mas_offset(-16);
        make.top.mas_equalTo(lb.mas_bottom).mas_offset(6);
    }];
    
    
    
    UIView *lineView = [[UIView alloc] init];
    [_tabHeaderView addSubview:lineView];
    lineView.backgroundColor = UIColorFromRGB(0xF8F8F8);
    [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_offset(0);
        make.top.mas_equalTo(lbDetail.mas_bottom).mas_offset(15);
        make.height.mas_equalTo(10);
    }];
    
    
    UILabel *lbTitle = [[UILabel alloc] init];
    lbTitle.text = @"热门推荐";
    lbTitle.font = FONT_BOLD(22);
    [_tabHeaderView addSubview:lbTitle];
    [lbTitle mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(lineView.mas_bottom);
        make.left.mas_offset(16);
        make.bottom.equalTo(self.tabHeaderView.mas_bottom);
        make.height.mas_equalTo(31);
    }];
    self.tabHeaderView.frame = CGRectMake(0, 0, SCREEN_WIDTH, GetViewYH(self.image3) + 150);
}

- (void)addNav {

    UIScrollView *scroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, kNavBarAndStatusBarHeight + 20)];
    [self.view addSubview:scroll];
    self.topNavScroll = scroll;
    scroll.backgroundColor = [UIColor clearColor];
    scroll.showsVerticalScrollIndicator = NO;
    scroll.showsHorizontalScrollIndicator = NO;
    scroll.contentSize = CGSizeMake(16+(20 + 80) * self.navDataArr.count, kNavBarAndStatusBarHeight + 20);
    
    for (int i = 0; i < self.navDataArr.count; i++) {
        UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(16 + (20 + 80) * i, kNavBarAndStatusBarHeight - ADAPT_W(30), 80, 34)];
        btn.tag = 10 + i;
        btn.titleLabel.font = FONT(16);
        if (i == 0) {
            btn.titleLabel.font = FONT_BOLD(24);
        }
        [btn setTitle:self.navDataArr[i] forState:UIControlStateNormal];
        
        [btn addTarget:self action:@selector(btnTopAction:) forControlEvents:UIControlEventTouchUpInside];
        [scroll addSubview:btn];
    }
}

- (void)btnTopAction:(UIButton *)sender {
    self.totalCount = 0;
    if (IsNotNilArr(self.dataArr)) {
        JSONDiscoverModel *model = self.dataArr[sender.tag - 10];
        self.topNavId = model.id;
        
        self.refreshCount = 1;
        
        for (int i = 0; i < self.navDataArr.count; i++) {
            UIButton *button = [self.view viewWithTag:10 + i];
            button.titleLabel.font = FONT(16);
        }
        sender.titleLabel.font = FONT_BOLD(24);
        self.index = sender.tag - 10;
        [self updateUIWith:self.dataArr index:self.index];
    }
}

#pragma mark - 友盟分享
- (void)shareAction:(UIButton *)sender {
    self.shareDicData = self.tableViewDataArr[sender.tag - 1000];
    
//    self.shareDataModel = self.tableViewDataArr[sender.tag - 1000];
 
    [self shareAlertView];
    //    友盟原生UI面板
    {
        //        [UMSocialUIManager setPreDefinePlatforms:@[
        //                                                   @(UMSocialPlatformType_QQ),
        //                                                   @(UMSocialPlatformType_WechatSession),
        //                                                   @(UMSocialPlatformType_UserDefine_Begin + 1)]];
        //        [UMSocialUIManager showShareMenuViewInWindowWithPlatformSelectionBlock:^(UMSocialPlatformType platformType, NSDictionary *userInfo) {
        //            // 根据获取的platformType确定所选平台进行下一步操作
        //            [self shareWebPageToPlatformType:platformType dic:dic];
        //        }];
    }
}

- (void)shareAlertView {
    UIWindow *window = [[UIApplication sharedApplication] keyWindow];
    //    蒙板
    UIView *view = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    view.tag = 9998;
    view.backgroundColor = [UIColor colorWithWhite:0 alpha:0.7];
    [window addSubview:view];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapRemoveShareView:)];
    [view addGestureRecognizer:tap];
    
    
    UIView *whiteView = [[UIView alloc] initWithFrame:CGRectMake(16, SCREEN_HEIGHT - 120 - 28, SCREEN_WIDTH - 32, 120)];
    whiteView.backgroundColor = [UIColor whiteColor];
    whiteView.tag = 9999;
    ViewBorderRadius(whiteView, 10, 0, [UIColor whiteColor]);
    [window addSubview:whiteView];
    
    //间距
    float weight = 65;
    int range = (whiteView.frame.size.width - weight * 4) / 5;
    NSArray *arr = @[@"微信",
                     @"朋友圈",
                     @"QQ"];
    
    for (int i = 0; i < arr.count; i++) {
        UIButton *imageBtn = [[UIButton alloc] initWithFrame:CGRectMake(range + i * (weight + range), 20, weight, weight)];
        [imageBtn setImage:[UIImage imageNamed:[NSString stringWithFormat:@"分享%d", i]] forState:UIControlStateNormal];
        [imageBtn addTarget:self action:@selector(shareBtnAction:) forControlEvents:UIControlEventTouchUpInside];
        imageBtn.tag = i + 10000;
        [imageBtn setTitle:arr[i] forState:UIControlStateNormal];
        [whiteView addSubview:imageBtn];
        
        UILabel *lb = [[UILabel alloc] initWithFrame:CGRectMake(range + i * (weight + range), GetViewYH(imageBtn), weight, 17)];
        lb.tag = i + 10010;
        lb.textColor = UIColorFromRGB(0x333333);
        lb.font = FONT(12);
        lb.text = arr[i];
        lb.textAlignment = 1;
        [whiteView addSubview:lb];
    }
    //    if (![QQApiInterface isQQInstalled]) {//没有安装QQ
    //        UIButton *btn = [whiteView viewWithTag:10002];
    //        btn.hidden = YES;
    //
    //        UILabel *lb = [whiteView viewWithTag:10012];
    //        lb.hidden = YES;
    //    }
    //    if (![WXApi isWXAppInstalled]) { //没有安装微信
    //        UIButton *btn0 = [whiteView viewWithTag:10000];
    //        UIButton *btn1 = [whiteView viewWithTag:10001];
    //        btn0.hidden = YES;
    //        btn1.hidden = YES;
    //
    //        UILabel *lb0 = [whiteView viewWithTag:10010];
    //        UILabel *lb1 = [whiteView viewWithTag:10011];
    //        lb0.hidden = YES;
    //        lb1.hidden = YES;
    //    }
}

- (void)shareBtnAction:(UIButton *)sender {
    [self removeShareView];
    NSInteger platformType = 0;
    switch (sender.tag) {
            case 10000: {
                platformType = 1;//微信聊天
            }
            break;
            case 10001: {
                platformType = 2;//微信朋友圈
            }
            break;
            case 10002: {
                platformType = 4;//QQ聊天
            }
            break;
            case 10003: {
                
                if ([UserManager sharedUserManager].isLogin) {
                    NSString *str = [NSString stringWithFormat:@"%@", self.shareDicData[@"id"]];
                    NSDictionary *par = @{@"userId":DSStringValue([UserManager sharedUserManager].userInfo.uid),
                                          @"tweetId":str
                                          };
                    
                    [PPNetworkHelper POST:URL_addCollect parameters:par success:^(id responseObject) {
                        [SXLoadingView showAlertHUD:responseObject[@"retMsg"] duration:SXLoadingTime];
                    } failure:^(NSError *error) {
                        [SXLoadingView showAlertHUD:SXLoadingErrorStr duration:SXLoadingTime];
                    }];
                } else {
                    LoginAndRegisterVC *vc = [[LoginAndRegisterVC alloc] init];
                    vc.hidesBottomBarWhenPushed = YES;
                    vc.pushType = 1;
                    [self.navigationController pushViewController:vc animated:YES];
                }
                return;
            }
            break;
            
        default:
            break;
    }
    //创建分享消息对象
    UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
    //创建网页内容对象
    NSString *thumbURL = [NSString stringWithFormat:@"%@", self.shareDicData[@"imgPath"]];
    UMShareWebpageObject *shareObject = [UMShareWebpageObject shareObjectWithTitle:[NSString stringWithFormat:@"%@", self.shareDicData[@"fromName"]] descr:[NSString stringWithFormat:@"%@", self.shareDicData[@"title"]] thumImage:thumbURL];
    //设置网页地址
    shareObject.webpageUrl = [NSString stringWithFormat:@"%@", self.shareDicData[@"linkPath"]];
    //分享消息对象设置分享内容对象
    messageObject.shareObject = shareObject;
    //调用分享接口
    [[UMSocialManager defaultManager] shareToPlatform:platformType messageObject:messageObject currentViewController:self completion:^(id data, NSError *error) {
        if (error) {
            UMSocialLogInfo(@"************分享失败 %@*********",error);
        } else {
            if ([data isKindOfClass:[UMSocialShareResponse class]]) {
                UMSocialShareResponse *resp = data;
                //分享结果消息
                UMSocialLogInfo(@"响应消息 %@",resp.message);
                //第三方原始返回的数据
                UMSocialLogInfo(@"原始响应数据 %@",resp.originalResponse);
            } else {
                UMSocialLogInfo(@"响应数据 %@",data);
            }
        }
    }];
}

- (void)tapRemoveShareView:(UITapGestureRecognizer *)tap {
    [self removeShareView];
}

- (void)removeShareView {
    UIWindow *window = [[UIApplication sharedApplication] keyWindow];
    UIView *view0 = [window viewWithTag:9998];
    UIView *view1 = [window viewWithTag:9999];
    
    [view0 removeFromSuperview];
    [view1 removeFromSuperview];
}


#pragma mark --UITableView代理

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    
    CGFloat navHeight = kNavBarAndStatusBarHeight + 20;
    CGFloat offset = scrollView.contentOffset.y;
    
    if (offset <= navHeight) {
        self.topNavScroll.backgroundColor = [UIColor clearColor];
        for (int i = 0; i < self.navDataArr.count; i++) {
            UIButton *btn = [self.view viewWithTag:10 + i];
            [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        }
    } else {

        self.topNavScroll.backgroundColor = [UIColor whiteColor];
     
        for (int i = 0; i < self.navDataArr.count; i++) {
            UIButton *btn = [self.view viewWithTag:10 + i];
            [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        }
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    //刷新数据处理
     self.tableView.mj_footer.hidden = (self.tableViewDataArr.count == 0);
     if (self.tableViewDataArr.count == self.totalCount) {
         [self.tableView.mj_footer endRefreshingWithNoMoreData];
     } else {
         [self.tableView.mj_footer endRefreshing];
     }
    return self.tableViewDataArr.count;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    
    WKWebViewController *webVC = [[WKWebViewController alloc] initWithURLString:self.tableViewDataArr[indexPath.row][@"linkPath"]];
    webVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:webVC animated:YES];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"DiscoverTableViewCell";
    DiscoverTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[DiscoverTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    cell.shareBtn.tag = indexPath.row + 1000;
    [cell.shareBtn addTarget:self action:@selector(shareAction:) forControlEvents:UIControlEventTouchUpInside];
    [cell updateDiscoverTableViewCellWithdata:self.tableViewDataArr[indexPath.row]];
    return cell;
}


- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] init];
        _tableView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - kTabBarHeight);
        _tableView.tableHeaderView = _tabHeaderView;
        _tableView.delegate = self;
        _tableView.dataSource  = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tableView registerNib:[UINib nibWithNibName:@"DiscoverTableViewCell" bundle:nil] forCellReuseIdentifier:@"DiscoverTableViewCell"];
    }
    return _tableView;
}


- (NSMutableArray *)dataArr {
    if (!_dataArr) {
        _dataArr = [[NSMutableArray alloc] init];
    }
    return _dataArr;
}

- (NSMutableArray *)tableViewDataArr {
    if (!_tableViewDataArr) {
        _tableViewDataArr = [[NSMutableArray alloc] init];
    }
    return _tableViewDataArr;
}

- (NSMutableArray *)navDataArr {
    if (!_navDataArr) {
        _navDataArr = [[NSMutableArray alloc] init];
    }
    return _navDataArr;
}

@end
